package com.learn.rpc.socket;

import com.learn.rpc.common.AdminUser;
import com.learn.rpc.common.IAdminUserService;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

/**
 * 伪代理,仅仅包装一下原本调用,提供一个独立的访问
 * @author wangxing
 * @version 2020/8/14 17:28 Administrator
 */
public class RogueProxyAdminUserServiceImpl implements IAdminUserService {
    @Override
    public AdminUser findAdminUserById(Integer id) {
        String host ="localhost";
        int port=8899;
        Socket s = null;
        try {
            s = new Socket(host,port);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            DataOutputStream dos = new DataOutputStream(baos);
            dos.writeInt(id);
            s.getOutputStream().write(baos.toByteArray());
            s.getOutputStream().flush();
            DataInputStream dis = new DataInputStream(s.getInputStream());
            int trunId = dis.readInt();
            String name = dis.readUTF();
            AdminUser user = new AdminUser(trunId,name);
            System.out.println(user);
            close(s, baos,dos,dis);
            return user;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public AdminUser findAdminUserByName(String name) {
        return null;
    }

    @Override
    public String getNameAndId(Integer id, String name) {
        return null;
    }

    public void close(Socket s ,ByteArrayOutputStream baos,DataOutputStream dos,DataInputStream dis ){
        try {
            dos.close();
            s.close();
            baos.close();
            dis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
